<template>

  <div>
    <!-- 顶部的面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
      <el-breadcrumb-item>厨师管理</el-breadcrumb-item>
      <el-breadcrumb-item>厨师列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!--添加按钮-->
    <el-row>
      <el-button type="primary" size="medium" @click="$router.push('/temp/chef/addNew')">添加</el-button>

      <el-button type="primary" @click="openAddDialog()">添加厨师分类</el-button>
      <el-divider content-position="left">厨师列表</el-divider>
    </el-row>
    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" align="center" width="80"></el-table-column>
      <el-table-column prop="name" label="姓名" align="center" width="100px"></el-table-column>
      <el-table-column prop="phoneNumber" label="手机号" width="120" align="center"></el-table-column>
      <el-table-column prop="password" label="密码" width="120" align="center"></el-table-column>
      <el-table-column prop="age" label="年龄" width="120" align="center"></el-table-column>
      <el-table-column prop="gender" label="性别" width="120" align="center"></el-table-column>
      <el-table-column label="图片" width="60" align="center">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.imgUrl"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="厨师介绍" width="120" align="center"></el-table-column>
      <el-table-column prop="appointment" label="可预约时间" width="120" align="center"></el-table-column>
      <el-table-column label="是否可预约" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.displayState"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" align="center"></el-table-column>
      <el-table-column prop="balance" label="余额" width="120" align="center"></el-table-column>

      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="info" icon="el-icon-user" circle size="mini"
                     @click="goToPerson(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin: 10px 0;text-align: right;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :hide-on-single-page="true"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="total">
      </el-pagination>
    </div>

    <!-- 修改数据的表单 -->
    <el-dialog title="修改厨师信息的表单" :visible.sync="editFormVisible">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="editForm.phoneNumber"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age"></el-input>
        </el-form-item>

        <!--修改图片    -->
        <el-form-item label="封面图" prop="imgUrl">
          <div class="picture-preview" v-if="editForm.imgUrl">
            <el-image class="image"
                      :src="editForm.imgUrl"
                      fit="cover"></el-image>
          </div>
          <el-upload
              class="picture-uploader"
              action="http://localhost:9523/resources/upload/image/chef/"
              :show-file-list="false"
              :on-success="handleUploadSuccess">
            <i class="el-icon-upload picture-uploader-icon"></i>
            <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
            <div class="picture-uploader-text">仅允许上传不超过 <i>5MB</i> 的图片</div>
          </el-upload>

        </el-form-item>

        <el-form-item label="厨师介绍" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>

        <el-form-item label="可预约时间" prop="appointment">
          <el-input v-model="editForm.appointment"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit('editForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加厨师分类的表单 -->
    <el-dialog title="添加厨师分类的表单" :visible.sync="addFormVisible">
      <el-form :model="addForm" :rules="editRules" ref="addForm" label-width="120px">
        <el-form-item label="厨师姓名" prop="chefName">
          <el-select v-model="addForm.chefName" placeholder="请选择" @change="handleChangeChef">
            <el-option
                v-for="c in chefs"
                :key="c.id"
                :label="c.name"
                :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="厨师分类" prop="did">
          <el-select v-model="addForm.did" placeholder="请选择">
            <el-option
                v-for="d in dish"
                :key="d.id"
                :label="d.name"
                :value="d.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd('addForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 0,
      total: 0,

      // 编辑对话框相关数据
      editFormVisible: false,
      editForm: {
        id: '',
        name: '',
        phoneNumber: '',
        password: '',
        age: '',
        gender: '',
        imgUrl: '',
        description: '',
        appointment: '',
        displayState: '',

      },
      //厨师数据
      chefs: [],
      //菜品分类数据
      dish: [],
      addFormVisible: false,
      addForm: {
        id: '',
        cid: '',
        did: '',
        chefName: ''
      },

      //编辑表单规则
      editRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {
            pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/,
            message: '姓名必须是2~10长度的字符组成，且不允许使用标点符号',
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: '请输密码', trigger: 'blur'},
          {min: 6, max: 16, message: '密码必须是6~16位长度,允许使用数字,子母,标点符号', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {pattern: /^(1[89]|[2-5][0-9]|6[0-5])$/, message: '年龄必须是18~65岁之间', trigger: 'blur'}
        ],
        imgUrl: [
          {required: true, message: '请上传图像', trigger: 'blur'},
          {pattern: /./, message: '请上正确格式', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请编写预约时间', trigger: 'blur'},
          {pattern: /./, message: '请写入正确格式', trigger: 'blur'}
        ],
        appointment: [
          {required: true, message: '请填写可预约时间', trigger: 'blur'},
          {pattern: /./, message: '请写入正确格式', trigger: 'blur'}
        ],
      },
      // 编辑表单的label宽度
      formLabelWidth: '120px'
    }
  },
  methods: {
    //跨页面传参
    goToPerson(id) {
      this.$router.push({
        path: '/temp/chef/person',
        query: {
          id: id
        }
      });
    },

    //厨师分类列表显示
    DishSelect() {
      let url = 'http://localhost:9523/menu/dishCategory/list';
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.dish = jsonResult.data.list;
          console.log("-----------------------"
              + this.dish)
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    //显示厨师列表
    loadChefLists() {
      let url = 'http://localhost:9523/chef/lists';
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.chefs = jsonResult.data.list;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //弹出添加厨师分类对话框
    openAddDialog() {
      this.addFormVisible = true;
    },


    handleChangeChef(value) {
      const selectedChef = this.chefs.find(chef => chef.id === value);
      if (selectedChef) {
        this.addForm.chefName = selectedChef.name;
        this.addForm.cid = selectedChef.id;
      } else {
        this.addForm.chefName = '';
      }
    },


    //添加厨师分类
    handleAdd(formName) {

      console.log("------------------" + this.addForm.chefName)
      console.log("------------------" + this.addForm.cid);
      console.log("------------------" + this.addForm.did);


      this.$refs[formName].validate((valid) => {

        if (valid) {
          let url = 'http://localhost:9523/chefDish/add/' + this.addForm.cid + "," + this.addForm.did + "," + this.addForm.chefName;
          console.log('url = ' + url);
          //let formData = this.qs.stringify(this.addForm);
          //console.log('formData = ' + formData);
          var chefName = decodeURIComponent(this.addForm.chefName);
          this.axios.get(url).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                message: '新增厨师分类成功！',
                type: 'success'
              });
              this.addFormVisible = false;
              //this.handleAdd(formName);
            } else {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          });
        }
      });
    },


    // 上传成功后的回调
    handleUploadSuccess(response) {
      console.log("------------------------------------------------" + response);
      this.editForm.imgUrl = response.data.url;
    },

    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadChefList();
    },
    //弹出修改对话框
    openEditDialog(tableItem) {
      let url = 'http://localhost:9523/chef/' + tableItem.id;
      console.log('url = ' + url);

      this.axios
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.editFormVisible = true;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadChefList();
            }
          });
        }
      });
    },
    // 执行修改
    handleEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = 'http://localhost:9523/chef/' + this.editForm.id + '/update/info';
          console.log('url = ' + url);

          let formData = this.qs.stringify(this.editForm);
          console.log('formData = ' + formData);

          this.axios
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                message: '修改厨师成功！',
                type: 'success'
              });
              this.editFormVisible = false;
              this.loadChefList();
            } else if (jsonResult.state == 40400) {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                  this.editFormVisible = false;
                  this.loadChefList();
                }
              });
            } else {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          });
        }
      });
    },


    //是否可以预约
    toggleEnable(tableItem) {
      let enableText = ['启用不可以', '启用可以'];
      let url = 'http://localhost:9523/chef/' + tableItem.id;
      if (tableItem.displayState == 0) {
        url += '/disable';
      } else {
        url += '/enable';
      }
      console.log('url = ' + url);

      this.axios
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: enableText[tableItem.displayState] + '预约！',
            type: 'success'

          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              if (jsonResult.state == 40400) {
                this.loadChefList();
              }
            }
          });
        }
        this.loadChefList();
      });
    },

    // 弹出删除确认框
    openDeleteConfirm(tableItem) {
      let message = '此操作将永久删除【' + tableItem.name + '】厨师，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(tableItem);
      }).catch(() => {
      });
    },
    // 执行删除
    handleDelete(tableItem) {
      let url = 'http://localhost:9523/chef/' + tableItem.id + '/delete';
      console.log('url = ' + url);

      this.axios
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除标签成功！',
            type: 'success'
          });
          this.loadChefList();
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },

    //显示厨师列表
    loadChefList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:9523/chef/list?page=' + page;
      console.log('url = ' + url);

      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadChefList();
    this.loadChefLists();
    this.DishSelect();
  }
}
</script>

<style>
.picture-uploader {
  float: left;
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.picture-uploader .picture-uploader-icon {
  width: 240px;
  height: 80px;
  font-size: 58px;
  color: #8c939d;
  line-height: 80px;
  text-align: center;
}

.picture-uploader .picture-uploader-text {
  width: 240px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 10px;
  color: #8c939d;
}

.picture-uploader .picture-uploader-text i {
  font-size: 10px;
  font-weight: bold;
  font-style: normal;
  color: #F56C6C;
}

.picture-preview {
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px solid #e8e6e6;
  border-radius: 6px;
  float: left;
  display: inline;
  position: relative;
}

.picture-preview .image {
  width: 240px;
  height: 135px;
  border-radius: 6px;
}
</style>
